package com.aiwiown.snackmq.broker.handler;

import com.aiwiown.snackmq.common.handler.MessageHandler;
import com.aiwiown.snackmq.common.handler.RequestContext;
import com.aiwiown.snackmq.common.message.Message;
import com.aiwiown.snackmq.common.message.MessageStatus;
import com.aiwiown.snackmq.common.message.MessageType;
import com.aiwiown.snackmq.network.connection.ConnectionManager;
import io.netty.channel.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 处理生产者注册请求。
 */
@Slf4j
@RequiredArgsConstructor
public class RegisterProducerHandler implements MessageHandler {

    private final ConnectionManager connectionManager;

    @Override
    public MessageType getMessageType() {
        return MessageType.REGISTER_PRODUCER_REQUEST;
    }

    @Override
    public void handle(RequestContext ctx, Message request) {
        String producerId = request.getProperty("producerId");
        Channel channel = (Channel) ctx.getChannel();

        if (producerId == null || producerId.isEmpty() || channel == null) {
            log.warn("Invalid RegisterProducerRequest: producerId or channel is null. Request: {}", request);
            ctx.writeResponse(Message.builder()
                    .type(MessageType.RESPONSE)
                    .messageId(request.getMessageId())
                    .status(MessageStatus.FAILED)
                    .errorMessage("Invalid request: producerId and channel must be present.")
                    .build());
            return;
        }

        try {
            connectionManager.registerProducer(producerId, channel);
            // 【核心修复】: 在成功注册后，必须向客户端发送一个成功响应。
            // 缺少这一步是导致客户端超时的根本原因。
            Message response = Message.builder()
                    .type(MessageType.RESPONSE)
                    .messageId(request.getMessageId())
                    .status(MessageStatus.SUCCESS)
                    .build();
            ctx.writeResponse(response);
            log.debug("Successfully registered producer '{}' with channel {}", producerId, channel.id().asShortText());
        } catch (Exception e) {
            log.error("Error registering producer '{}'", producerId, e);
            ctx.writeResponse(Message.builder()
                    .type(MessageType.RESPONSE)
                    .messageId(request.getMessageId())
                    .status(MessageStatus.FAILED)
                    .errorMessage("Internal server error during producer registration: " + e.getMessage())
                    .build());
        }
    }

//    @Override
//    public void handle(RequestContext ctx, Message request) {
//        String producerId = request.getProperty("producerId");
//        if (producerId != null && !producerId.isEmpty()) {
//            // 【修复】现在可以从 RequestContext 获取 channel 对象
//            Object channelObject = ctx.getChannel();
//            if (channelObject instanceof Channel) {
//                // 将 producerId 与其当前的 channel 关联起来
//                connectionManager.registerProducer(producerId, (Channel) channelObject);
//            } else {
//                log.error("Could not register producer '{}' because the channel object in RequestContext is not a valid Netty Channel. Actual type: {}",
//                        producerId, channelObject != null ? channelObject.getClass().getName() : "null");
//            }
//        } else {
//            log.warn("Received a producer registration request with a missing producerId.");
//        }
//        // 这是一个注册操作，不需要向客户端发送响应
//    }
}